package com.bianguo.android.functiondemo.model;

import com.bianguo.android.functiondemo.retrofit.ApiService;
import com.bianguo.android.functiondemo.utils.MLog;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class ModelFactory {

    private static volatile ModelFactory mFactory;
//    public static final String BASE_URL = "https://api.douban.com/v2/movie/";
//    public static final String BASE_URL = "http://192.168.0.18:8081/WebServletDemo_war_exploded/";
    public static final String BASE_URL = "http://192.168.0.18:8080/";
    public ApiService apiService;

    private ModelFactory() {

        OkHttpClient mClient = new OkHttpClient.Builder()
                .readTimeout(15, TimeUnit.SECONDS)
                .connectTimeout(15, TimeUnit.SECONDS)
                .addInterceptor(createHttpLoggingInterceptor())
                .addInterceptor(createTelephoneInterceptor())
                .build();

        Retrofit mRetrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(mClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        apiService = mRetrofit.create(ApiService.class);
    }

    private Interceptor createHttpLoggingInterceptor() {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(message -> MLog.mLog("Retrofit", "https ---> " + message));
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        return loggingInterceptor;
    }

    private Interceptor createTelephoneInterceptor() {
        return new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                Headers headers = request.headers();
                String method = request.method();
                MLog.mLog("request headers = " + headers + ", method = " + method);
                RequestBody body = request.body();
                if (body instanceof FormBody) {
                }
                return chain.proceed(request);
            }
        };
    }

    public static ModelFactory getInstance() {
        ModelFactory modelFactory = mFactory;
        if (modelFactory == null) {
            synchronized (ModelFactory.class) {
                if (modelFactory == null) {
                    modelFactory = new ModelFactory();
                    mFactory = modelFactory;
                }
            }
        }
        return modelFactory;
    }
}
